/*
 * This class is coded to read AppConfig.xml file
 * for toolbar generation configuration
 */
package com.meraklisina.latexeditor;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 
 * @author kursattopcu
 */
public class AppConfigReader {

	private String configFilePath;

	public AppConfigReader(String configFilePath) {
		this.configFilePath = configFilePath;
	}

	public String getConfigFilePath() {
		return configFilePath;
	}

	public void setConfigFilePath(String configFilePath) {
		this.configFilePath = configFilePath;
	}

	/**
	 * 
	 * @return List of LatexToolBar(s) that taken from configuration file. This
	 *         list holds visible and hidden toolbars.
	 */
	public ArrayList<LatexToolBar> GetToolBarList() {
		ArrayList<LatexToolBar> toolbarList = new ArrayList<LatexToolBar>();
		XmlHandler appHandler = new XmlHandler(getConfigFilePath());
		NodeList nodeLst = appHandler.GetElementsByTagName("ToolBar");
		for (int s = 0; s < nodeLst.getLength(); s++) {
			Node toolBarNode = nodeLst.item(s);
			NamedNodeMap attrs = toolBarNode.getAttributes();
			Node nameAttribute = attrs.getNamedItem("name");
			System.out.println(nameAttribute.getNodeValue());
			Node visibleAttribute = attrs.getNamedItem("visible");
			String toolbarName = nameAttribute.getNodeValue();
			boolean available = false;
			if (visibleAttribute != null) {
				available = "Y".equals(visibleAttribute.getNodeValue());
			}
			Node orderAttribute = attrs.getNamedItem("order");
			if (orderAttribute != null) {
				int order = Integer.parseInt(orderAttribute.getNodeValue());
				toolbarList.add(new LatexToolBar(toolbarName, toolbarName,
						available, order));
			} else {
				toolbarList.add(new LatexToolBar(toolbarName, toolbarName,
						available));
			}

		}
		// sort by order
		ToolBarHandler.sort(toolbarList);

		return toolbarList;
	}

	/**
	 * State of the toolbars can be kept with this utility.
	 * 
	 * @param xmlString
	 *            String to be written to file
	 */
	public void writeToolbarConfigFile(String xmlString) {
		try {
			FileWriter fw = new FileWriter(new File(this.getConfigFilePath()));
			fw.write(xmlString);
			fw.flush();
			fw.close();
		} catch (IOException ex) {
			Logger.getLogger(AppConfigReader.class.getName()).log(Level.SEVERE,
					null, ex);
		}
	}
}
